<style lang="less">
    @import '../../../styles/common.less';
</style>
<style>
    .ivu-table .demo-table-info-row td{
        background-color: #2db7f5;
        color: #fff;
    }
</style>

<template>
  <div style="position: relative">
      <Spin size="large" fix v-if="isLoading"></Spin>
      <Row>
        <Col span="24">
            <Card>
                <p slot="title">
                    <!-- <Icon type="android-more-horizontal"></Icon> -->
                    菜单列表
                </p>
                <Row>
                    <Col span="3" offset="21">
                        <span style="margin: 0 10px;" v-if="$hasPerms('menu:save')">
                            <Button type="primary" icon="plus" @click="handleAdd('')">新增菜单</Button>
                        </span>
                    </Col>
                </Row>
                <br>
                <Row>
                    <tree-grid 
                        :items="catalog"
                        :columns="columns"
                        @on-row-click="rowClick"
                    >
                    </tree-grid>
                </Row>
            </Card>
        </Col>
      </Row>
      <Modal
              class="autoHeight"
              v-model="addModal"
              :title="modalTitle"
              :mask-closable="false">
        <div>
        <Form ref="addFrom" :model="addFrom" label-position="left" :label-width="80" :rules="rules">
            <FormItem label="类型">
                <RadioGroup ref="type" v-model="addFrom.type" @on-change="menuTypeChange">
                    <Radio :label=1>目录</Radio>
                    <Radio :label=2>菜单</Radio>
                    <Radio :label=3>按钮</Radio>
                </RadioGroup>
            </FormItem> 
            <FormItem label="菜单名称" prop="name">
                <Input ref="name" v-model="addFrom.name"></Input>
            </FormItem>
            <FormItem label="上级菜单">
                <Select ref="pid" v-model="addFrom.pid" :disabled="pmenuEnable">
                    <Option  v-for="menu in pmenus" v-bind:value="menu.id" v-bind:key="menu.id">{{menu.title}}</Option>
                </Select>
            </FormItem> 
            <!-- <FormItem label="菜单路由">
                <Input ref="url" v-model="addFrom.url"></Input>
            </FormItem> -->
            <FormItem label="授权标识">
                <Input ref="permission" :disabled="permsEnable" v-model="addFrom.permission" placeholder="多个请用逗号分割比如：sys:menu:list,sys:menu:add,..."></Input>
            </FormItem>
            <FormItem label="菜单排序">
                <InputNumber ref="sort" v-model="addFrom.sort"></InputNumber>
            </FormItem>
            <FormItem label="菜单图标">
                <Select ref="icon" v-model="addFrom.icon">
                    <Option v-for="ic in icons" :value="ic.value" :key="ic.value">
                        <Icon :type="ic.value"></Icon>{{ic.label}}
                    </Option>
                </Select>
            </FormItem>
        </Form>
        </div>
        <div slot="footer">
            <Button type="text" @click="cancelModal">取消</Button>
            <Button type="primary" :loading="saveLoading" @click="addModalOk">保存</Button>
        </div>
      </Modal>
  </div>
</template>

<script>
import TreeGrid from '../../my-components/tree-table/tree-grid.vue';
import menuIcons from './menu_icon.js';
import colData from './menu-col.js';

export default {
    name: 'menu-table',
    components: {
        TreeGrid
    },
    data () {
        return {
            modalTitle: '',
            isLoading: true,
            saveLoading: false,
            // 表头
            columns: colData.columns,
            // 数据
            menuList: [],
            catalog: [],
            menu: [],
            icons: menuIcons,
            addModal: false,
            pmenus: [],
            selectedMenus: [],
            pmenuEnable: false,
            permsEnable: true,
            addFrom: {
                id: 0,
                pid: 0,
                type: 0,
                icon: '',
                name: '',
                url: '',
                permission: '',
                sort: 0
            },
            rules: {
                name: [
                    {required: true, message: '名称不能为空', trigger: 'blur'}
                ]
            }
        };
    },
    methods: {
        getData () {
            this.isLoading = true;
            this.$get('/menu/list')
                .then(res => {
                    this.catalog = [];
                    this.menuList = res;
                    this.getParentMenus();
                    this.isLoading = false;
                })
                .catch(error => {
                    this.isLoading = false;
                    this.$Message.error(error.message);
                });
        },
        menuTypeChange () {
            if (this.addFrom.type === 1) {
                // 目录
                this.pmenus = this.selectedMenus;
                this.addFrom.pid = this.selectedMenus[0].id;
                this.pmenuEnable = true;
                this.permsEnable = true;
                this.addFrom.pid = 0;
            } else if (this.addFrom.type === 2) {
                // 菜单
                this.addFrom.permission = '';
                this.pmenuEnable = false;
                this.permsEnable = true;
                this.pmenus = this.selectedMenus.filter(p => {
                    return p.type == 1;
                });
                this.addFrom.pid = this.pmenus[0].id;
            } else {
                // 按钮
                this.pmenuEnable = false;
                this.permsEnable = false;
                this.pmenus = this.selectedMenus.filter(p => {
                    return p.type == 2;
                });
                this.addFrom.pid = this.pmenus[0].id;
            }
        },
        rowClick (data, key, index, tetx) {
            if (key === 'edit') {
                this.handleEdit(data.id);
            }
            if (key === 'delete') {
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>您确定要删除这条数据吗？</p>',
                    onOk: () => {
                        this.handleDel(data);
                    }
                });
            }
        },
        cancelModal () {
            this.addModal = false;
        },
        handleAdd (rowVal) {
            this.modalTitle = '菜单添加';
            this.addFrom.type = 1;
            this.addFrom.id = 0;
            this.getPmenus();
            this.pmenuEnable = true;
            this.addModal = true;
        },
        handleEdit (menuId) {
            this.$get('/menu/info/' + menuId)
                .then(res => {
                    this.modalTitle = '菜单编辑';
                    this.getPmenus();
                    this.addFrom.id = res.id;
                    this.addFrom.pid = res.parentId;
                    this.addFrom.icon = res.icon;
                    this.addFrom.name = res.title;
                    this.addFrom.sort = res.sorts;
                    this.addFrom.type = res.type;
                    this.addFrom.permission = res.perms;
                    if (res.type === 3) {
                        this.permsEnable = false;
                    }
                    this.addModal = true;
                }).catch(error => {
                    console.log(error);
                    this.$Message.error('获取菜单信息失败');
                });
        },
        addModalOk () {
            this.$refs.addFrom.validate((valid) => {
                if (valid) {
                    this.saveLoading = true;
                    let url = this.addFrom.id === 0 ? '/menu/save' : '/menu/update';
                    this.$post(url, {
                        id: this.addFrom.id === 0 ? null : this.addFrom.id,
                        type: this.addFrom.type,
                        parentId: this.addFrom.pid,
                        icon: this.addFrom.icon,
                        title: this.addFrom.name,
                        // url: this.addFrom.url,
                        perms: this.addFrom.permission,
                        sorts: this.addFrom.sort
                    }, 'json')
                        .then(res => {
                            this.getData();
                            this.$Message.success('操作成功');
                            this.addModal = false;
                            this.saveLoading = false;
                        })
                        .catch(error => {
                            this.saveLoading = false;
                            this.$Message.error(error.message);
                        });
                } else {
                    let fields = this.$refs.addFrom.fields;
                    try {
                        fields.forEach(element => {
                            if (element.validateState === 'error') {
                                // 这里的element无foucs()
                                let refName = element.prop;
                                this.$refs[refName].focus();
                                foreach.break = new Error('StopIteration');
                            }
                        });
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },
        handleDel (menu) {
            let menuIds = [];
            menuIds.push(menu.id);
            this.$del('/menu/delete', menuIds, 'json')
                .then(res => {
                    this.getData();
                    this.$Message.success('删除了' + menu.title);
                }).catch(error => {
                    this.$Message.error(error.message);
                });
        },
        getPmenus () {
            this.$get('/menu/select')
                .then(res => {
                    this.pmenus = res;
                    this.selectedMenus = res;
                })
                .catch(error => {
                    this.$Message.error('获取下拉菜单信息失败');
                });
        },
        getParentMenus () {
            let parentMenus = this.menuList.filter(item => {
                return item.type === 1;
            });
            let subMenus = this.menuList.filter(item => {
                return item.type === 2;
            });
            subMenus.forEach(item => {
                item.children = this.getChildrenMenu(item.id);
                this.menu.push(item);
            });
            parentMenus.forEach(item => {
                item.children = this.getChildrenMenu(item.id);
                this.catalog.push(item);
            });
        },
        getChildrenMenu (parentId) {
            let childrens = [];
            this.menuList.forEach((item, index) => {
                if (item.parentId === parentId) {
                    childrens.push(item);
                }
            });
            return childrens;
        }
    },
    created () {
        this.getData();
    }
};
</script>
